const { src, dest, series, parallel, watch } = require('gulp');
const browserSync = require('browser-sync')
const gulpLoadPlugins = require('gulp-load-plugins')
const del = require('del');

const DIST_OUTPUT = 'dist';
const TEMP_OUTPUT = '.temp';
const input = (path = '') => 'src' + path
const plugins = gulpLoadPlugins();
const bs = browserSync.create()

const data = {
  menus: [
    {
      name: 'Home',
      icon: 'aperture',
      link: 'index.html'
    },
    {
      name: 'Features',
      link: 'features.html'
    },
    {
      name: 'About',
      link: 'about.html'
    },
    {
      name: 'Contact',
      link: '#',
      children: [
        {
          name: 'Twitter',
          link: 'https://twitter.com/w_zce'
        },
        {
          name: 'About',
          link: 'https://weibo.com/zceme'
        },
        {
          name: 'divider'
        },
        {
          name: 'About',
          link: 'https://github.com/zce'
        }
      ]
    }
  ],
  pkg: require('./package.json'),
  date: new Date()
}

const lint = () =>
  src(input('/**/*.js'))
    .pipe(plugins.eslint({
      rules: {
        'strict': 2
      },
      globals: [
        '$'
      ],
      env: {
        'browser': true,
        'es6': true,
      },
      parserOptions: {
        ecmaVersion: 6
      }
    }))
    .pipe(plugins.eslint.format())
    .pipe(plugins.eslint.failAfterError())

const clean = () => del([DIST_OUTPUT, TEMP_OUTPUT])

const script = () =>
  src(input('/**/*.js'))
    .pipe(plugins.babel({ presets: ['@babel/preset-env'] }))
    .pipe(dest(TEMP_OUTPUT))
    .pipe(bs.reload({ stream: true }))

const style = () =>
  src(input('/**/*.scss'))
    .pipe(plugins.sass({ outputStyle: 'expanded' }))
    .pipe(dest(TEMP_OUTPUT))
    .pipe(bs.reload({ stream: true }))

const page = () =>
  src(input('/**/*.html'))
    .pipe(plugins.swig({ data, defaults: { cache: false } }))
    .pipe(dest(TEMP_OUTPUT))
    .pipe(bs.reload({ stream: true }))

const public = () => {
  return src('public/**', { base: 'public' })
    .pipe(dest(DIST_OUTPUT))
}

const image = () =>
  src(input('/assets/images/**'), { base: 'src' })
    .pipe(plugins.imagemin())
    .pipe(dest(DIST_OUTPUT))

const fonts = () =>
  src(input('/assets/fonts/**'), { base: 'src' })
    .pipe(plugins.imagemin())
    .pipe(dest(DIST_OUTPUT))

const server = () => {
  watch('src/assets/styles/*.scss', style);
  watch('src/assets/scripts/*.js', script);
  watch('src/**/*.html', page);
  watch([
    'src/assets/images/**',
    'src/assets/fonts/**',
    'public/**'
  ], bs.reload);

  bs.init({
    notify: false,
    port: 2080,
    server: {
      baseDir: [TEMP_OUTPUT, 'src', 'public'],
      routes: {
        '/node_modules': 'node_modules'
      }
    }
  })
}

const useref = () => {
  return src('.temp/*.html', { base: TEMP_OUTPUT })
    .pipe(plugins.useref({ searchPath: [TEMP_OUTPUT, '.'] }))
    .pipe(plugins.if(/\.js$/, plugins.uglify()))
    .pipe(plugins.if(/\.css$/, plugins.cleanCss()))
    .pipe(plugins.if(/\.html$/, plugins.htmlmin({
      collapseWhitespace: true,
      minifyCSS: true,
      minifyJS: true
    })))
    .pipe(dest(DIST_OUTPUT))
}

const compile = parallel(style, script, page);

const serve = series(compile, server)

const start = serve;

const build = series(
  clean,
  parallel(
    series(compile, useref),
    image,
    fonts,
    public
  )
)

module.exports = {
  clean,
  serve,
  style,
  start,
  build,
  lint
}
